package com.yami.shop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yami.shop.bean.app.dto.CarUserManDto;
import com.yami.shop.bean.app.param.CarUserAuthParam;
import com.yami.shop.bean.app.param.CarUserReviewParam;
import com.yami.shop.bean.model.CarUser;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.PageAdapter;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.CarUserMapper;
import com.yami.shop.service.CarUserService;
import org.springframework.stereotype.Service;

/**
 * CarUserServiceImpl
 *
 * @Author Administrator
 * @Date 2025/4/14 13:18
 */
@Service
public class CarUserServiceImpl extends ServiceImpl<CarUserMapper, CarUser> implements CarUserService {
    @Override
    public CarUser getUserByOpenId(String openId) {
        return this.baseMapper.getUserByOpenId(openId);
    }

    @Override
    public void submitAuth(CarUserAuthParam param) {
        Integer userId = param.getUserId();
        CarUser carUser1 = baseMapper.selectById(userId);
        if(carUser1.getStatus() == 1){
            throw new YamiShopBindException("请等待审核");
        }
        String ridgepole = param.getRidgepole();
        Integer roomNumber = Integer.valueOf(param.getRoomNumber());
        String formattedNumber = String.format("%04d", roomNumber);
        Integer roomId = Integer.valueOf(ridgepole + formattedNumber);
        CarUser carUser2 = baseMapper.getUserByRoomId(roomId);
        if(ObjectUtil.isNotNull(carUser2) && carUser2.getUserId() != userId){
            throw new YamiShopBindException("该房号已被绑定");
        }
        CarUser carUser = BeanUtil.copyProperties(param, CarUser.class);
        carUser.setStatus(0);
        carUser.setRoomId(roomId);
        baseMapper.updateById(carUser);
    }

    @Override
    public IPage<CarUserManDto> userList(PageParam<CarUserManDto> page, Integer userId) {
        CarUser carUser1 = baseMapper.selectById(userId);
        if(carUser1.getSuperAdmin() != 1){
            throw new YamiShopBindException("您没有权限");
        }
        page.setRecords(baseMapper.userList(new PageAdapter(page)));
        page.setTotal(baseMapper.countUserList());
        return page;
    }

    @Override
    public void review(Integer manUserId, CarUserReviewParam param) {
        CarUser carUser1 = baseMapper.selectById(manUserId);
        if(carUser1.getSuperAdmin() != 1){
            throw new YamiShopBindException("您没有权限");
        }
        Integer authType = param.getAuthType();
        CarUser carUser = baseMapper.selectById(param.getUserId());
        if(ObjectUtil.isNull(carUser)){
            throw new YamiShopBindException("该用户不存在");
        }
        carUser.setStatus(authType);
        carUser.setFailedCause(param.getFailedCause());
        baseMapper.updateById(carUser);
    }
}
